﻿using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.PL;
using Apps.Models.PL;
using Apps.IBLL.PL;
using System.Data.Entity;

namespace Apps.BLL.PL
{
    public partial class PL_HC_PLANSBLL : IPL_HC_PLANSBLL
    {
         
        [Dependency]
        public IPL_HC_PLANSRepository m_Rep { get; set; }
        [Dependency]
        public IPL_HC_DETAILSRepository m_DRep { get; set; }
        public virtual List<PL_HC_PLANSModel> GetList(ref GridPager pager, string queryStr, string sDate, string eDate)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    var whereLambda = PredicateBuilder.True<V_PL_HC_PLANS>();
                    if (!string.IsNullOrEmpty(queryStr))
                    {
                        whereLambda = whereLambda.And(p => p.PLAN_ID.Contains(queryStr));
                    }
                    if (string.IsNullOrWhiteSpace(sDate))
                    {
                        sDate = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd");
                    }
                    if (string.IsNullOrWhiteSpace(eDate))
                    {
                        eDate = DateTime.Now.AddMonths(1).ToString("yyyy-MM-dd");
                    }
                    DateTime dt1 = Convert.ToDateTime(sDate + " 00:00:00");
                    DateTime dt2 = Convert.ToDateTime(eDate + " 23:59:59");

                    whereLambda = whereLambda.And(p => DateTime.Compare((DateTime)p.START_TIME, dt1) >= 0 && DateTime.Compare((DateTime)p.START_TIME, dt2) <= 0);
                    var queryData = db.V_PL_HC_PLANS.Where(whereLambda.Compile()).AsQueryable();

                    pager.totalRows = queryData.Count();
                    //排序
                    queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                    return CreateModelList(ref queryData);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }


        public virtual List<PL_HC_PLANSModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<PL_HC_PLANS> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
                                a => a.PLAN_ID.Contains(queryStr)
                                || a.PLAN_USER_ID.Contains(queryStr)
                                );
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<PL_HC_PLANSModel> GetPagerList(ref GridPager pager, Expression<Func<PL_HC_PLANS, bool>> whereLambda)
        {
            IQueryable<PL_HC_PLANS> queryData = m_Rep.GetList(whereLambda);
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<PL_HC_PLANS> GetList(Expression<Func<PL_HC_PLANS, bool>> whereLambda)
        {
            try
            {
                IQueryable<PL_HC_PLANS> queryData = m_Rep.GetList().Where(whereLambda.Compile()).AsQueryable(); ;
                return queryData.ToList();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public virtual List<PL_HC_PLANSModel> GetListByParentId(ref GridPager pager, string queryStr, object parentId)
        {
            return new List<PL_HC_PLANSModel>();
        }

        public virtual List<PL_HC_PLANSModel> CreateModelList(ref IQueryable<PL_HC_PLANS> queryData)
        {
            var queryResult = from m1 in queryData
                              select new PL_HC_PLANSModel()
                              {
                                  PLAN_ID = m1.PLAN_ID,
                                  WAYBILL = m1.WAYBILL,
                                  BATCH_CODE = m1.BATCH_CODE,
                                  WEIGHT = m1.WEIGHT,
                                  SEND_STATION_ID = m1.SEND_STATION_ID,
                                  ARRIVE_STATION_ID = m1.ARRIVE_STATION_ID,
                                  MATERIEL_ID = m1.MATERIEL_ID,
                                  SUPPLIER_ID = m1.SUPPLIER_ID,
                                  PLAN_USER_ID = m1.PLAN_USER_ID,
                                  PLAN_USER_NAME = "",
                                  SEND_STATION = "",
                                  ARRIVE_STATION = "",
                                  MATERIEL_NAME = "",
                                  SUPPLIER_NAME = "",
                                  CREATE_TIME = m1.CREATE_TIME.ToString(),
                                  PUBLISHED = m1.PUBLISHED,
                                  PUBLISH_TIME = m1.PUBLISH_TIME,
                                  START_TIME = m1.START_TIME.ToString(),
                                  END_TIME = m1.END_TIME.ToString(),
                                  ARTIFICIAL_CODE = m1.ARTIFICIAL_CODE,
                                  BWEIGHT = m1.BWEIGHT,
                                  MINE_ID = m1.MINE_ID,
                                  MINE_NAME = "",
                                  USTART_TIME = m1.USTART_TIME.ToString(),
                                  UEND_TIME = m1.UEND_TIME.ToString(),
                                  UNLOAD_USER_ID = "",
                                  UNLOAD_USER_NAME = "",
                                  UCREATE_TIME = "",
                                  STOCKPILE_ID = "",
                                  STOCKPILE_NAME = "",
                                  CARS_NUM = 0,
                                  REMARK = m1.REMARK
                              };
            return queryResult.ToList();
        }

        public virtual List<PL_HC_PLANSModel> CreateModelList(ref IQueryable<V_PL_HC_PLANS> queryData)
        {
            //var queryDetail = (from m7 in m_Rep.Context.PL_HC_DETAILS
            //                   group m7 by m7.PLAN_ID into a
            //                   select new 
            //                   {
            //                       PLAN_ID = a.Key,
            //                       CAR_NUM = string.Join(",", a.Select(i => i.CAR_NUM))
            //                   }).AsQueryable();
            //var queryPlan = (from m1 in queryData
            //                 join m8 in queryDetail on m1.PLAN_ID equals m8.PLAN_ID
            //                 select new PL_HC_PLANSModel()
            //                 {
            //                     PLAN_ID = m1.PLAN_ID,
            //                     WAYBILL = m1.WAYBILL,
            //                     BATCH_CODE = m1.BATCH_CODE,
            //                     WEIGHT = m1.WEIGHT,
            //                     SEND_STATION_ID = m1.SEND_STATION_ID,
            //                     ARRIVE_STATION_ID = m1.ARRIVE_STATION_ID,
            //                     MATERIEL_ID = m1.MATERIEL_ID,
            //                     SUPPLIER_ID = m1.SUPPLIER_ID,
            //                     PLAN_USER_ID = m1.PLAN_USER_ID,
            //                     CREATE_TIME = m1.CREATE_TIME,
            //                     PUBLISHED = m1.PUBLISHED,
            //                     PUBLISH_TIME = m1.PUBLISH_TIME,
            //                     START_TIME = m1.START_TIME,
            //                     END_TIME = m1.END_TIME,
            //                     ARTIFICIAL_CODE = m1.ARTIFICIAL_CODE,
            //                     BWEIGHT = m1.BWEIGHT,
            //                     CAR_NUM = m8.CAR_NUM
            //                 }).AsQueryable();

            var queryResult = from m1 in queryData
                              select new PL_HC_PLANSModel()
                              {
                                  PLAN_ID = m1.PLAN_ID,
                                  WAYBILL = m1.WAYBILL,
                                  BATCH_CODE = m1.BATCH_CODE,
                                  WEIGHT = m1.WEIGHT,
                                  SEND_STATION_ID = m1.SEND_STATION_ID,
                                  ARRIVE_STATION_ID = m1.ARRIVE_STATION_ID,
                                  MATERIEL_ID = m1.MATERIEL_ID,
                                  SUPPLIER_ID = m1.SUPPLIER_ID,
                                  PLAN_USER_ID = m1.PLAN_USER_ID,
                                  PLAN_USER_NAME = m1.PLAN_USER_NAME,
                                  SEND_STATION = m1.SEND_STATION,
                                  ARRIVE_STATION = m1.ARRIVE_STATION,
                                  MATERIEL_NAME = m1.MATERIEL_NAME,
                                  SUPPLIER_NAME = m1.SUPPLIER_NAME,
                                  CREATE_TIME = m1.CREATE_TIME.ToString(),
                                  PUBLISHED = m1.PUBLISHED,
                                  PUBLISH_TIME = m1.PUBLISH_TIME,
                                  START_TIME = m1.START_TIME.ToString(),
                                  END_TIME = m1.END_TIME.ToString(),
                                  ARTIFICIAL_CODE = m1.ARTIFICIAL_CODE,
                                  BWEIGHT = m1.BWEIGHT,
                                  MINE_ID = m1.MINE_ID,
                                  MINE_NAME = m1.MINE_NAME,
                                  USTART_TIME = m1.USTART_TIME.ToString(),
                                  UEND_TIME = m1.UEND_TIME.ToString(),
                                  UNLOAD_USER_ID = m1.UNLOAD_USER_ID,
                                  UNLOAD_USER_NAME = m1.UNLOAD_USER_NAME,
                                  UCREATE_TIME = m1.UCREATE_TIME.ToString(),
                                  STOCKPILE_ID = m1.STOCKPILE_ID,
                                  STOCKPILE_NAME = m1.STOCKPILE_NAME,
                                  CARS_NUM = m1.CARS_NUM,
                                  REMARK = m1.REMARK
                                  //TRAIN_TYPE_ID=m1.TRAIN_TYPE_ID
                              };
            return queryResult.ToList();
        }

        public virtual bool Create(ref ValidationErrors errors, PL_HC_PLANSModel model)
        {
            try
            {
                PL_HC_PLANS entity = m_Rep.GetById(model.PLAN_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new PL_HC_PLANS();
                entity.PLAN_ID = model.PLAN_ID;
                entity.WAYBILL = model.WAYBILL;
                entity.BATCH_CODE = model.BATCH_CODE;
                entity.WEIGHT = model.WEIGHT;
                entity.SEND_STATION_ID = model.SEND_STATION_ID;
                entity.ARRIVE_STATION_ID = model.ARRIVE_STATION_ID;
                entity.MATERIEL_ID = model.MATERIEL_ID;
                entity.SUPPLIER_ID = model.SUPPLIER_ID;
                entity.PLAN_USER_ID = model.PLAN_USER_ID;
                entity.CREATE_TIME = DateTime.Parse(model.CREATE_TIME);
                entity.PUBLISHED = model.PUBLISHED;
                entity.PUBLISH_TIME = model.PUBLISH_TIME;
                entity.START_TIME = DateTime.Parse(model.START_TIME);
                entity.END_TIME = DateTime.Parse(model.END_TIME);
                entity.ARTIFICIAL_CODE = model.ARTIFICIAL_CODE;
                entity.BWEIGHT = model.BWEIGHT;
                entity.MINE_ID = model.MINE_ID;
                entity.REMARK = model.REMARK;

                PL_HC_DETAILSBLL dll = new PL_HC_DETAILSBLL();
                if (m_Rep.Create(entity))
                {
                    //dll.Create(ref errors, item);
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }


        public virtual bool Deletes(ref ValidationErrors errors, Expression<Func<PL_HC_PLANS, bool>> whereLambda)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {

                    foreach (var entity in db.PL_HC_PLANS.Where(whereLambda))
                    {
                        db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                    }

                    if (db.SaveChanges() > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }


        public virtual bool Edit(ref ValidationErrors errors, PL_HC_PLANSModel model)
        {
            try
            {
                PL_HC_PLANS entity = m_Rep.GetById(model.PLAN_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                entity.PLAN_ID = model.PLAN_ID;
                entity.WAYBILL = model.WAYBILL;
                entity.BATCH_CODE = model.BATCH_CODE;
                entity.WEIGHT = model.WEIGHT;
                entity.SEND_STATION_ID = model.SEND_STATION_ID;
                entity.ARRIVE_STATION_ID = model.ARRIVE_STATION_ID;
                entity.MATERIEL_ID = model.MATERIEL_ID;
                entity.SUPPLIER_ID = model.SUPPLIER_ID;
                entity.PLAN_USER_ID = model.PLAN_USER_ID;
                entity.CREATE_TIME = DateTime.Parse(model.CREATE_TIME);
                entity.PUBLISHED = model.PUBLISHED;
                entity.PUBLISH_TIME = model.PUBLISH_TIME;
                entity.START_TIME = DateTime.Parse(model.START_TIME);
                entity.END_TIME = DateTime.Parse(model.END_TIME);
                entity.ARTIFICIAL_CODE = model.ARTIFICIAL_CODE;
                entity.BWEIGHT = model.BWEIGHT;
                entity.MINE_ID = model.MINE_ID;
                entity.REMARK = model.REMARK;

                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public bool EditUpload(ref ValidationErrors errors, PL_HC_PLANSModel model)
        {
            try
            {
                PL_HC_PLANS entity = m_Rep.GetById(model.PLAN_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                entity.PLAN_ID = model.PLAN_ID;
                entity.USTART_TIME = DateTime.Parse(model.USTART_TIME);
                entity.UEND_TIME = DateTime.Parse(model.UEND_TIME);


                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual PL_HC_PLANSModel GetById(object id)
        {
            if (IsExists(id))
            {
                PL_HC_PLANS entity = m_Rep.GetById(id);
                PL_HC_PLANSModel model = new PL_HC_PLANSModel();
                model.PLAN_ID = entity.PLAN_ID;
                model.WAYBILL = entity.WAYBILL;
                model.BATCH_CODE = entity.BATCH_CODE;
                model.WEIGHT = entity.WEIGHT;
                model.SEND_STATION_ID = entity.SEND_STATION_ID;
                model.ARRIVE_STATION_ID = entity.ARRIVE_STATION_ID;
                model.MATERIEL_ID = entity.MATERIEL_ID;
                model.SUPPLIER_ID = entity.SUPPLIER_ID;
                model.PLAN_USER_ID = entity.PLAN_USER_ID;
                model.CREATE_TIME = entity.CREATE_TIME.ToString();
                model.PUBLISHED = entity.PUBLISHED;
                model.PUBLISH_TIME = entity.PUBLISH_TIME;
                model.START_TIME = entity.START_TIME.ToString();
                model.END_TIME = entity.END_TIME.ToString();
                model.ARTIFICIAL_CODE = entity.ARTIFICIAL_CODE;
                model.BWEIGHT = entity.BWEIGHT;

                model.MINE_ID = entity.MINE_ID;
                model.USTART_TIME = entity.USTART_TIME.ToString();
                model.UEND_TIME = entity.UEND_TIME.ToString();
                model.REMARK = entity.REMARK;

                return model;
            }
            else
            {
                return null;
            }
        }

        public virtual PL_HC_PLANSModel GetItem(Expression<Func<PL_HC_PLANS, bool>> whereLambda)
        {

            PL_HC_PLANS entity = m_Rep.GetItem(whereLambda);
            if (entity == null) return null;

            PL_HC_PLANSModel model = new PL_HC_PLANSModel();
            model.PLAN_ID = entity.PLAN_ID;
            model.WAYBILL = entity.WAYBILL;
            model.BATCH_CODE = entity.BATCH_CODE;
            model.WEIGHT = entity.WEIGHT;
            model.SEND_STATION_ID = entity.SEND_STATION_ID;
            model.ARRIVE_STATION_ID = entity.ARRIVE_STATION_ID;
            model.MATERIEL_ID = entity.MATERIEL_ID;
            model.SUPPLIER_ID = entity.SUPPLIER_ID;
            model.PLAN_USER_ID = entity.PLAN_USER_ID;
            model.CREATE_TIME = entity.CREATE_TIME.ToString();
            model.PUBLISHED = entity.PUBLISHED;
            model.PUBLISH_TIME = entity.PUBLISH_TIME;
            model.START_TIME = entity.START_TIME.ToString();
            model.END_TIME = entity.END_TIME.ToString();
            model.ARTIFICIAL_CODE = entity.ARTIFICIAL_CODE;
            model.BWEIGHT = entity.BWEIGHT;
            model.REMARK = entity.REMARK;

            return model;
        }


        /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<PL_HC_PLANSModel> list, ref ValidationErrors errors)
        {

            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
            excelFile.AddMapping<PL_HC_PLANSModel>(x => x.PLAN_ID, "PLAN_ID");
            excelFile.AddMapping<PL_HC_PLANSModel>(x => x.PLAN_USER_ID, "PLAN_USER_ID");
            excelFile.AddMapping<PL_HC_PLANSModel>(x => x.CREATE_TIME, "CREATE_TIME");
            excelFile.AddMapping<PL_HC_PLANSModel>(x => x.PUBLISHED, "PUBLISHED");
            excelFile.AddMapping<PL_HC_PLANSModel>(x => x.PUBLISH_TIME, "PUBLISH_TIME");

            //SheetName
            var excelContent = excelFile.Worksheet<PL_HC_PLANSModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new PL_HC_PLANSModel();
                entity.PLAN_ID = row.PLAN_ID;
                entity.PLAN_USER_ID = row.PLAN_USER_ID;
                entity.CREATE_TIME = row.CREATE_TIME;
                entity.PUBLISHED = row.PUBLISHED;
                entity.PUBLISH_TIME = row.PUBLISH_TIME;

                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<PL_HC_PLANSModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        PL_HC_PLANS entity = new PL_HC_PLANS();
                        model.PLAN_ID = entity.PLAN_ID;
                        model.WAYBILL = entity.WAYBILL;
                        model.BATCH_CODE = entity.BATCH_CODE;
                        model.WEIGHT = entity.WEIGHT;
                        model.SEND_STATION_ID = entity.SEND_STATION_ID;
                        model.ARRIVE_STATION_ID = entity.ARRIVE_STATION_ID;
                        model.MATERIEL_ID = entity.MATERIEL_ID;
                        model.SUPPLIER_ID = entity.SUPPLIER_ID;
                        model.PLAN_USER_ID = entity.PLAN_USER_ID;
                        model.CREATE_TIME = entity.CREATE_TIME.ToString();
                        model.PUBLISHED = entity.PUBLISHED;
                        model.PUBLISH_TIME = entity.PUBLISH_TIME;
                        model.START_TIME = entity.START_TIME.ToString();
                        model.END_TIME = entity.END_TIME.ToString();
                        model.ARTIFICIAL_CODE = entity.ARTIFICIAL_CODE;
                        model.BWEIGHT = entity.BWEIGHT;
                        model.REMARK = entity.REMARK;


                        db.PL_HC_PLANS.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
        public void Dispose()
        {
             
        }

    }
}
